<?php

class Lingkungan extends Eloquent {
    protected $table        = 'lingkungan';
    static public $logoPath = "/img/lingkungan/";
    static public $ttdPath  = "/img/lingkungan/ttd";

    // Add your validation rules here
    public static $rules = [
        'nama'              => 'required',
        'kepala_desa'       => 'required',
        'kepala_lingkungan' => 'required',
        'lat_lng'           => 'required',
        'zoom'              => 'required|integer',
        'telp_ling'         => 'required',
        'telp_lurah'        => 'required'
    ];

    // Don't forget to fill this array
    protected $fillable = [
        'nama',
        'kepala_desa',
        'kepala_lingkungan',
        'lat_lng',
        'zoom',
        'keterangan',
        'logo_kop_surat',
        'ttd_kepling',
        'ttd_keldat',
        'using_kepling',
        'using_keldat',
        'telp_ling',
        'telp_lurah',
        'polygon',
        'provinsi_id',
        'kabupaten_id',
        'kecamatan_id',
        'kelurahan_id',
        'is_active',
        'ref_id',
        'user_id',
        'action',
        'harga_prov',
        'harga_luar_prov',
        'lama_prov',
        'lama_luar_prov',
        'satuan_prov',
        'satuan_luar_prov'
    ];

    public function scopeActive($query) {
        return $query->where('is_active', '=', '1');
    }

    public function getLatLngAttribute($value)
    {
        return explode('|', $value);
    }

    public function getPolygonAttribute($value)
    {
        $result_coordinates = array();

        $coordinates = explode('|', $value);
        foreach ($coordinates as $coordinate) {
            $lat_lng = explode(',', $coordinate);
            array_push($result_coordinates, array('lat' => $lat_lng[0], 'lng' => $lat_lng[1]));            
        }        
        return $result_coordinates;        
    }

    public static function boot()
    {
        parent::boot();

        static::creating(function($lokasi)
        {
            $lokasi->user_id = Auth::user()->id;
        });
        
        static::updated(function($lokasi)
        {
           $lokasi->user_id = Auth::user()->id; 
        });        
    }
}